<template>
 
  <a-drawer
    :title="user.u_name+'的角色'"
    placement="right"
    :closable="true"
    v-model:visible="visible" 
    
  >
  <div style="margin-bottom:12px;">
      <a-button type="primary" style="width:100px;" @click="setRoles" >确定</a-button>
  </div>
   
   <a-checkbox-group v-model:value="roleIds">
       <div v-for="ro in roles" :key="ro.ro_id" style="padding:10px 5px;">
        <a-checkbox  :value="ro.ro_id"   >{{ro.ro_name}}</a-checkbox>
       </div>
   </a-checkbox-group>
  </a-drawer>
</template>
<script>
import {ref } from 'vue';
import {get , put ,tip} from '@/common';
export default{
  setup() {
    const visible = ref(false);//本抽屉是否可见

    const user = ref({});//用户
    const roles = ref([]);//角色列表
    const roleIds = ref([]);//选中的角色编号

    const open = (uObj) => {//打开抽屉
      user.value = uObj;

      
      /* 访问用户角色列表获取接口，响应数据格式如下：
       * [
           {ro_id:1,ro_name:'xxxxx',has:true},
           {ro_id:2,ro_name:'yyyy',has:false},
           ......
         ]       
       */
      get('/security/user/role/'+user.value.u_id).then(res=>{
          roles.value = res.data;
          const temp = [];
          for(let i=0;i<roles.value.length;i++){
              if(roles.value[i].has){
                  temp.push(roles.value[i].ro_id);//将选中角色的id放入数组
              }
          }
          roleIds.value = temp;
      });



      visible.value = true;
    };


    //设置角色
    const setRoles = ()=>{
        put('/security/user/role/'+user.value.u_id,roleIds.value).then(res=>{
            tip.success('角色设置成功！');
        });
    };

    return {
      visible,      
      open,
      user,//用户
      roles,
      roleIds,//选中的角色编号
      setRoles,
    };
  },
};
</script>